#!/bin/bash

# FFmpeg快速编译脚本
# 使用方法: ./quick_build.sh [android|ios|all]

set -e

PLATFORM=${1:-"all"}

echo "🚀 开始编译FFmpeg..."

# 检查环境
check_environment() {
    echo "检查编译环境..."
    
    if [ "$PLATFORM" = "android" ] || [ "$PLATFORM" = "all" ]; then
        if [ -z "$ANDROID_NDK_ROOT" ]; then
            echo "❌ 错误: 请设置ANDROID_NDK_ROOT环境变量"
            echo "例如: export ANDROID_NDK_ROOT=/path/to/android-ndk"
            exit 1
        fi
        
        if [ ! -d "$ANDROID_NDK_ROOT" ]; then
            echo "❌ 错误: ANDROID_NDK_ROOT路径不存在: $ANDROID_NDK_ROOT"
            exit 1
        fi
        
        echo "✅ Android NDK路径: $ANDROID_NDK_ROOT"
    fi
    
    if [ "$PLATFORM" = "ios" ] || [ "$PLATFORM" = "all" ]; then
        if ! command -v xcrun &> /dev/null; then
            echo "❌ 错误: 未找到Xcode工具链"
            exit 1
        fi
        
        echo "✅ Xcode工具链可用"
    fi
}

# 创建目录结构
setup_directories() {
    echo "创建目录结构..."
    mkdir -p android/app/src/main/jniLibs
    mkdir -p ios/FFmpeg/lib
    mkdir -p ios/FFmpeg/include
}

# 编译Android
build_android() {
    echo "📱 开始编译Android版本..."
    
    # 修改脚本中的NDK路径
    sed -i "s|/path/to/android-ndk|$ANDROID_NDK_ROOT|g" scripts/build_ffmpeg_android.sh
    
    # 执行编译
    chmod +x scripts/build_ffmpeg_android.sh
    ./scripts/build_ffmpeg_android.sh
    
    echo "✅ Android编译完成"
}

# 编译iOS
build_ios() {
    echo "🍎 开始编译iOS版本..."
    
    # 执行编译
    chmod +x scripts/build_ffmpeg_ios.sh
    ./scripts/build_ffmpeg_ios.sh
    
    echo "✅ iOS编译完成"
}

# 验证编译结果
verify_build() {
    echo "验证编译结果..."
    
    if [ "$PLATFORM" = "android" ] || [ "$PLATFORM" = "all" ]; then
        echo "检查Android库文件..."
        if [ -d "android/app/src/main/jniLibs/arm64-v8a" ]; then
            echo "✅ Android库文件已生成"
            ls -la android/app/src/main/jniLibs/arm64-v8a/
        else
            echo "❌ Android库文件未找到"
        fi
    fi
    
    if [ "$PLATFORM" = "ios" ] || [ "$PLATFORM" = "all" ]; then
        echo "检查iOS库文件..."
        if [ -d "ios/FFmpeg/lib" ]; then
            echo "✅ iOS库文件已生成"
            ls -la ios/FFmpeg/lib/
        else
            echo "❌ iOS库文件未找到"
        fi
    fi
}

# 主函数
main() {
    echo "🎯 FFmpeg快速编译工具"
    echo "目标平台: $PLATFORM"
    echo ""
    
    check_environment
    setup_directories
    
    if [ "$PLATFORM" = "android" ] || [ "$PLATFORM" = "all" ]; then
        build_android
    fi
    
    if [ "$PLATFORM" = "ios" ] || [ "$PLATFORM" = "all" ]; then
        build_ios
    fi
    
    verify_build
    
    echo ""
    echo "🎉 编译完成！"
    echo ""
    echo "📁 输出目录:"
    echo "  Android: android/app/src/main/jniLibs/"
    echo "  iOS: ios/FFmpeg/"
    echo ""
    echo "🔧 下一步:"
    echo "  1. 检查库文件是否正确生成"
    echo "  2. 运行项目测试编译"
    echo "  3. 验证FFmpeg功能"
}

# 执行主函数
main
